// pages/auth/forgot-password.ts
import { AuthAPI } from '../../utils/api'

Page({
  data: {
    statusBarHeight: 0,
    formData: {
      phone: '',
      smsCode: '',
      newPassword: '',
      confirmPassword: ''
    },
    showNewPassword: false,
    showConfirmPassword: false,
    smsCountdown: 0,
    loading: false
  },

  onLoad(options: any) {
    const systemInfo = wx.getSystemInfoSync();
    this.setData({
      statusBarHeight: systemInfo.statusBarHeight || 0
    });

    // 如果从登录页传入了手机号，自动填充
    if (options.phone) {
      this.setData({
        'formData.phone': options.phone
      });
    }
  },

  // 输入框变化
  onInputChange(e: any) {
    const field = e.currentTarget.dataset.field;
    const value = e.detail.value;
    this.setData({
      [`formData.${field}`]: value
    });
  },

  // 切换密码可见性
  togglePasswordVisibility(e: any) {
    const field = e.currentTarget.dataset.field;
    this.setData({
      [field]: !this.data[field]
    });
  },

  // 验证手机号
  validatePhone(phone: string): boolean {
    return /^1[3-9]\d{9}$/.test(phone);
  },

  // 发送短信验证码
  async sendSmsCode() {
    const { phone } = this.data.formData;

    if (!this.validatePhone(phone)) {
      wx.showToast({
        title: '请输入正确的手机号',
        icon: 'none'
      });
      return;
    }

    try {
      await AuthAPI.sendSmsCode({
        phone: phone,
        type: 'register'  // 重置密码使用register类型
      });

      // 开始倒计时
      this.startCountdown();

      wx.showToast({
        title: '验证码已发送',
        icon: 'success'
      });

    } catch (error: any) {
      console.error('发送验证码失败:', error);

      let errorMsg = '发送失败，请重试';
      if (error.msg) {
        errorMsg = error.msg;
      } else if (error.data && error.data.msg) {
        errorMsg = error.data.msg;
      }

      wx.showToast({
        title: errorMsg,
        icon: 'none',
        duration: 2000
      });
    }
  },

  // 开始倒计时
  startCountdown() {
    this.setData({ smsCountdown: 60 });

    const timer = setInterval(() => {
      const countdown = this.data.smsCountdown - 1;
      
      if (countdown <= 0) {
        clearInterval(timer);
        this.setData({ smsCountdown: 0 });
      } else {
        this.setData({ smsCountdown: countdown });
      }
    }, 1000);
  },

  // 验证表单
  validateForm(): boolean {
    const { phone, smsCode, newPassword, confirmPassword } = this.data.formData;

    if (!this.validatePhone(phone)) {
      wx.showToast({
        title: '请输入正确的手机号',
        icon: 'none'
      });
      return false;
    }

    if (!smsCode.trim()) {
      wx.showToast({
        title: '请输入验证码',
        icon: 'none'
      });
      return false;
    }

    if (smsCode.length !== 6) {
      wx.showToast({
        title: '验证码必须为6位',
        icon: 'none'
      });
      return false;
    }

    if (!newPassword.trim() || newPassword.length < 8) {
      wx.showToast({
        title: '新密码为8-20位',
        icon: 'none'
      });
      return false;
    }

    // 验证密码格式（必须包含字母和数字）
    const passwordRegex = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,20}$/;
    if (!passwordRegex.test(newPassword)) {
      wx.showToast({
        title: '密码必须包含字母和数字',
        icon: 'none',
        duration: 2000
      });
      return false;
    }

    if (newPassword !== confirmPassword) {
      wx.showToast({
        title: '两次密码不一致',
        icon: 'none'
      });
      return false;
    }

    return true;
  },

  // 提交重置密码
  async submitReset() {
    if (!this.validateForm()) {
      return;
    }

    this.setData({ loading: true });

    try {
      const response = await AuthAPI.forgotPassword(this.data.formData);

      if (response.code === 200) {
        wx.showToast({
          title: '密码重置成功',
          icon: 'success',
          duration: 2000
        });

        // 2秒后返回登录页面
        setTimeout(() => {
          wx.navigateBack({
            success: () => {
              // 通知登录页面填入手机号
              const pages = getCurrentPages();
              if (pages.length > 0) {
                const prevPage = pages[pages.length - 1];
                if (prevPage && typeof prevPage.setData === 'function') {
                  prevPage.setData({
                    loginPhone: this.data.formData.phone,
                    loginMode: 'password'
                  });
                }
              }
            }
          });
        }, 2000);
      } else {
        this.setData({ loading: false });
        wx.showToast({
          title: response.msg || '重置失败',
          icon: 'none',
          duration: 2000
        });
      }

    } catch (error: any) {
      this.setData({ loading: false });

      let errorMsg = '重置失败，请重试';
      if (error.msg) {
        errorMsg = error.msg;
      } else if (error.data && error.data.msg) {
        errorMsg = error.data.msg;
      }

      wx.showToast({
        title: errorMsg,
        icon: 'none',
        duration: 2500
      });
    }
  },

  // 返回
  goBack() {
    wx.navigateBack({
      delta: 1
    });
  }
});






